package com.xcc.httpUtils.request;

import com.xcc.httpUtils.utils.StringUtils;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.util.Map;

/**
 * Created by Carman on 2017/7/7.
 * OkHttpRequest 抽象类.<br></>
 * 配置信息处理类.
 * <p>
 * 添加 RequestBody <br></>
 * 获取 Request <br></>
 * 添加 Headers <br></>
 * <p>
 * 修改: 2017年9月3日18:03:46
 * <p>
 * 解决错误 URL 导致程序异常崩溃.
 */
public abstract class BaseHttpRequest {

    protected final static MediaType JSON_MEDIA = MediaType.parse("application/json;charset=UTF-8");

    protected String url;  //请求连接
    protected Object tag;  //标记
    protected Map<String, String> params;  //请求参数
    protected Map<String, String> headers;  //头参数
    protected Request.Builder builder = new Request.Builder();
    protected String mJson;

    protected BaseHttpRequest(String url, Object tag,
                              Map<String, String> params, Map<String, String> headers, String json) {
        this.url = url;
        this.tag = tag == null ? url : tag; // tag 为空默认使用 url
        this.params = params;
        this.headers = headers;
        addJson(json);
        try {
            initBuilder();
            appendHeaders(); //添加头信息
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加 json 参数
     *
     * @param json
     * @return
     */
    public BaseHttpRequest addJson(String json) {
        if(!StringUtils.isEmpty(json)){ // 添加 json 参数
            mJson = json;
        }
        return this;
    }

    /**
     * 初始化一些基本参数 url , tag , headers
     */
    private void initBuilder() {
        builder.url(url).tag(tag);
    }

    /**
     * 生成 RequestCall 实例对象
     *
     * @return RequestCall 实例对象
     */
    public RequestCall build() {
        return new RequestCall(this);
    }

    /**
     * 生成 OkHttp Request 实例对象
     *
     * @return Request 实例对象
     */
    public Request generateRequest() {
        RequestBody requestBody = buildRequestBody();
        Request request = buildRequest(requestBody);
        return request;
    }

    /**
     * 添加头参数
     */
    protected void appendHeaders() {
        Headers.Builder headerBuilder = new Headers.Builder();
        if (headers == null || headers.isEmpty()) return;
        for (String key : headers.keySet()) {
            headerBuilder.add(key, headers.get(key));
//            builder.addHeader(key, headers.get(key));
        }
        builder.headers(headerBuilder.build());
    }

    /**
     * 生成 RequestBody 实例对象<br></>
     * 自定义 RequestBody 实例对象
     *
     * @return
     */
    abstract protected RequestBody buildRequestBody();

    /**
     * 生成 request 对象
     *
     * @param requestBody RequestBody 实例对象
     * @return request 实例对象
     */
    abstract protected Request buildRequest(RequestBody requestBody);
}
